<template>
  <div class="list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <div class="header">
        <div class="header-warp">
          <el-button text type="primary" icon="el-icon-plus" @click="handleAddCourse">
            添加课程
          </el-button>
          <el-button text type="danger" icon="el-icon-delete" :disabled="currentItem.length <= 0" @click="batchDeletion">
            批量删除
          </el-button>
        </div>
      </div>
      <div>
        <el-table style="width: 100%;" :data="courseList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" />
          <el-table-column label="封面" align="center">
            <template v-slot="{ row }">
              <el-image class="courseAvatar" :src="row.cover">
                <div slot="error">
                  <div class="image-slot">暂无图片</div>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="课程标题" align="center" />
          <el-table-column prop="day" label="完成天数" align="center" />
          <el-table-column label="完成进度" align="center">
            <template slot-scope="scope">
              {{ Math.round(scope.row.allSchedule*100) }}%
            </template>
          </el-table-column>
          <el-table-column label="课程完成时间" prop="pivot.completion" align="center" />
          <el-table-column label="创建时间" prop="created_at" align="center" />
          <el-table-column align="center" prop="action" label="操作">
            <template v-slot="{ row }">
              <el-button circle plain icon="el-icon-view" @click="detail(row)" />
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteCourse(row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      title="添加课程"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-table style="width: 100%" :data="course" @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column label="封面" align="center">
          <template v-slot="{ row }">
            <el-image class="courseAvatar" :src="row.cover">
              <div slot="error">
                <div class="image-slot">暂无图片</div>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="day" label="完成天数" align="center" />
      </el-table>
      <Pagination :total="page.total" :limit="page.paginate" @pagination="pagination" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCourse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { course, addUserCourse, deleteUserCourses, courseList } from '@/api/train'
import {deleteCourseToUser,getCourseListByUserSelected,getCourseListNoSelected,addCourseToUser} from '@/api/v2/course'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      courseList: [],
      dialogVisible: false,
      page: {
        paginate: 10,
        total: 0,
        page: 1
      },
      course: [],
      currentItem: [],
      userId: ''
    }
  },
  created() {
    this.userId = this.$route.query.id
    this.showCourse()
    // this.getTrainingList()
  },
  methods: {
    async detail(row) {
      this.$router.push({
        path: `/train/detail/${row.id}`
      })
    },
    handleAddCourse() {
      this.getUserNoCourseList()
      this.dialogVisible = true
    },
    async getUserNoCourseList(){
      const {data} = await getCourseListNoSelected({user_id: this.userId})
      this.course=data
    },
    async showCourse() {
      const {data} = await getCourseListByUserSelected({user_id: this.userId})
      this.courseList=data
    },
    // 多选
    handleSelectionChange(e) {
      this.currentItem = e.map(item => item.id)
    },
    async addCourse() {
      try {
        const ids = JSON.stringify(this.currentItem)
        console.log(ids,'ids');
        console.log(ids)
        const params = {
          user_id: this.userId,
          course_id: ids
        }

        await addCourseToUser(params)
          .catch(err => {
            throw new Error(value(err, 'response.data.message', '添加课程失败'))
          })

        await this.showCourse()
          .catch(err => {
            throw new Error(value(err, 'response.data.message', '添加课程失败'))
          })

        this.dialogVisible = false
        this.currentItem = []
        this.$message({
          message: '添加课程成功',
          type: 'success'
        })
        this.showCourse()
      } catch (e) {
        this.dialogVisible = false
        this.$message.error(e.message)
      }
    },
    pagination(e) {
      this.page.page = e.page
      this.page.paginate = e.limit
      this.showCourse()
    },
    // 删除课程
    deleteCourse(row) {
      const params = {
        user_id: this.$route.query.id,
        ids: JSON.stringify([row.id])
      }
      this.$confirm('是否删除课程', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCourseToUser(params)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '删除课程成功'
              })
              this.showCourse()
            })
        })
    },
    // 批量删除
    async batchDeletion() {
      this.$confirm('是否删除所选中的课程', '提示', { type: 'warning' })
        .then(() => {
          const ids = JSON.stringify(this.currentItem)
          this.batchDeletionApi(ids)
        })
    },
    async batchDeletionApi(ids) {
      const params = {
        user_id: this.$route.query.id,
        ids: ids
      }
      deleteCourseToUser(params)
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除课程成功'
          })
          this.showCourse()
        })
    }
  }
}
</script>
<style scoped lang='scss'>
.header{
  display: flex;
}
.header-warp {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.list{
    padding: 20px;
}
.courseAvatar{
    width: 60px;
    height: 60px;
  }
  .image-slot{
    width: 60px;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    background: #F5F7FA;
    color: #C0C4CC;
  }
</style>
